﻿/* ==============================================================================
* 功能描述：EventHandler
* 创 建 者：青金石
* 创建日期：2020/5/24 10:12:42
* ==============================================================================*/

using System;
using TCPServer.script.db;
using TCPServer.script.net;

public class EventHandler
{
    public static void OnTime()
    {
        CheckPing();
        RoomManager.Update();
    }

    /// <summary>
    /// 处理玩家断开连接
    /// </summary>
    /// <param name="state"></param>
    public static void OnDisConnect(ClientState state)
    {
        Console.WriteLine("Close");
        if (state.player != null)
        {
            //加入房间后离线,自动退出房间
            int roomId = state.player.roomID;
            if (roomId >= 0)
            {
                Room room = RoomManager.GetRoom(roomId);
                room.RemovePlayer(state.player.id);
            }
            //保存数据
            DBManager.UpdatePlayerData(state.player.id, state.player.data);
            //移除下线玩家
            PlayerManager.RemovePlayer(state.player.id);
        }
    }

    //ping检查
    private static void CheckPing()
    {
        //现在的时间戳
        long timeNow = NetManager.GetTimeStamp();
        //遍历所有客户端连接，超时的删除
        foreach (ClientState state in NetManager.clients.Values)
        {
            if (timeNow - state.lastPingTime > NetManager.pingInterval * 4)
            {
                Console.WriteLine("Ping Close " + state.socket.RemoteEndPoint.ToString());
                NetManager.Close(state);
                return;
            }
        }
    }
}